import React from 'react';
import { DatePicker, Toast } from 'antd-mobile';
import CountDown from './Countdown';

// 时间选择器的子组件
const CustomChildren = ({ extra, onClick, children }) => (
  <div onClick={onClick}>
    {extra}
  </div>
);

export default class extends React.Component {
  constructor(props) {
    super(props);
  }

  /**
   * 修改时间
   * @param {时间} time
   * @param {开始或结束时间} type true : 开始时间
   */
  changeTime = (time, type) => {
    time = time.getTime();
    if (type) {
      if (time > Date.now()) {
        Toast.info('该时间还没到', 2, null, false);
        return;
      }
      if (time > this.props.end) {
        Toast.info('还不能时光倒流', 2, null, false);
        return;
      }
    } else {
      if (time < this.props.start) {
        Toast.info('还不能时光倒流', 2, null, false);
        return;
      }
    }
    this.props.update(time, type);
  }

  render() {
    let { start, end } = this.props;
    start = start && new Date(start);
    end = end && new Date(end);
    return <div 
      style={{ color: '#888', display: 'flex', flex: 1, lineHeight: '22px', justifyContent: 'space-between' }}>
      <div style={{ display: 'flex' }}>
        {start ? <DatePicker
          mode="time"
          title="开始时间"
          minuteStep={1}
          use12Hours
          onChange={time=>{this.changeTime(time, true)}}
          value={start}>
          <CustomChildren />
        </DatePicker> : ''}
        <div style={{ margin: '0 4px' }}> - </div>
        {end ? <DatePicker
          mode="time"
          title="完成时间"
          minuteStep={1}
          minuteStep={1}
          use12Hours
          onChange={time=>{this.changeTime(time)}}
          value={end}
        >
          <CustomChildren />
        </DatePicker> : ''}
      </div>
      <CountDown start={start} end={end} />
    </div>
  }
}